/*!	@brief Create a ray ( wich can be a straight line, half-line or segment) 
 *	and check in every Entity is the ray intersect with a Entity's Face
 */

Raycast = function (){}



Raycast.Ray_PlaneIntersection	=	function(ray, plane)
{
	// We must determine the cartesian equation of our droite
	
	var numerateur 		=  -plane.a*ray.m_StartPosition.x 
-plane.b*ray.m_StartPosition.y - plane.c*ray.m_StartPosition.z - plane.d;
	var denominateur	= ray.m_Direction.x + ray.m_Direction.y + 
ray.m_Direction.z ;
	var K = 	numerateur/denominateur;
	
	return new Vec4(ray.m_StartPosition.x + K*ray.m_Direction.x, 
	ray.m_StartPosition.y + K*ray.m_Direction.y, 
	ray.m_StartPosition.z + K*ray.m_Direction.z);
	
}

/*!	brief An Intersection object store every intersection point for a given 
entity	*/
Intersection	=	function(entity, points)
{
	this.m_Entity	=	entity;
	this.m_Points 	=	point;
	
}
/*!	brief Look for intersection between a given ray and all Application 
Entities. Return an "Intersection" object
 */
Raycast.CheckIntersection			=	function(ray)
{
	//	Store all Intersection object we extracted from the current ray
	
	var entitiesIntersected	=	new Array();
	
	for(var i =0; i< Entity.Entities.length; i++)
	{
		var entity = Entity.Entities[i];
		
		if(entity.m_Mesh !=undefined)
		{
			var mesh = entity.m_Mesh;
			
			//	Store all intersection point between the ray and the
			// current Entity's mesh.
	
			var	intersectionPoints = new Array();
			
			var	isEntityIntersected	=	false;
			
			for(var j=0;j < mesh.m_Faces.length;j++)
			{
				var face = mesh.m_Faces[j];
				var intersectionPoint =Raycast.IntersectToFace(ray, face) ;
				
				if( intersectionPoint !=undefined)
				{
					intersectionPoints.push(intersectionPoint);
					isEntityIntersected=true;
				}
			}
			
			if(isEntityIntersected==true)
			{
				entitiesIntersected = new Intersection(entity, intersectionPoints);
			}
		}
	}
	
	// Now, we shoudl have a list with all entities intersected,
	// and theirs intersection points, so, it's time to compare every
	// intersection point 
	// to determine the one closer to the "start " point of the ray
	
	var startPoint = ray.m_StartPoint;
	var lengthCloserPoint=-1;
	var	closerPoint;
	var closerEntity;
	
	for(var i =0; i< entitiesIntersected.length; i++)
	{
		var points = entitiesIntersected[i].m_Points;
		
		for(var j=0;j<points.length; j++)
		{
			var point = points[j];
			
			var u	=	point.Minus(startPoint);
			u	=	u.Length();
			
			if(u<lengthCloserPoint || lengthCloserPoint==-1)
			{
				lengthCloserPoint	=	u;
				closerPoint			=	point;
				closerEntity		=	entitiesIntersected[i].m_Entity;
			}
		}
	}
}


